package com.situ.onlinebookstore.back.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.onlinebookstore.back.service.GoodsService;
import com.situ.onlinebookstore.common.entity.Goods;
import com.situ.onlinebookstore.common.mapper.GoodsMapper;
import com.situ.onlinebookstore.common.mapper.GoodsPicMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class GoodsServiceImpl implements GoodsService {
    private final GoodsMapper goodsMapper;
    private final GoodsPicMapper goodsPicMapper;

    @Override
    @Transactional(
            rollbackFor = Exception.class,
            isolation = Isolation.READ_COMMITTED,
            propagation = Propagation.REQUIRED
    )
    public int add(Goods goods, String[] pics) throws Exception {
        //添加商品时，要添加图片，三个核心技术
        //1-保存商品到数据库中 获取商品的ID
        int res = goodsMapper.insert(goods); //执行完之后，自增主键就放到了goods对象的id属性中
        //2-保存商品的图片 还需要商品ID
        if (pics != null && pics.length > 0) {
            res = goodsPicMapper.batchInsert(goods.getId(), pics);
        }
        return res;

    }

    @Override
    @Transactional
    public int edit(Goods goods, String[] pics) throws Exception {
        //修改商品时
        int res = goodsMapper.update(goods);
        //可能修改图片
        if (pics != null) {
            //删除原有的所有图片
            res = goodsPicMapper.deleteByGoodsId(goods.getId());
            if (pics.length>0){
                //重新插入所有图片
                res = goodsPicMapper.batchInsert(goods.getId(), pics);
            }
        }
        return res;
    }

    @Override
    public Goods getById(Integer id) {
        return goodsMapper.selectById(id);
    }

    @Override
    public List search(Goods goods) {
        return goodsMapper.select(goods);
    }

    @Override
    public PageInfo searchForPage(Integer page, Integer limit, Goods goods) {
        PageHelper.startPage(page, limit);
        List list = goodsMapper.select(goods);
        return new PageInfo(list);

    }
}
